<?php

namespace app\wxoa\service;

use app\common\model\ContestModel;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;

use Naixiaoxin\ThinkWechat\Facade;
use app\wxoa\model\template\TemplateFactory;

// use think\facade\Log;
use think\Queue;
use app\wxoa\job\TemplateMessage;

class SchoolMessageService
{
    protected $type;
    /**
     * @NEW_CONTEST_START_MESSAGE 新活动开始通知
     * @SCHOOL_APPLY_SUCCESS_MESSAGE 活动报名成功通知
     * @SCHOOL_SUBMIT_WORK_END_MESSAGE 学校提交作品即将结束通知
     * @SCHOOL_VATE_START_MESSAGE 投票开始通知
     * @SCHOOL_VATE_END_BEFORE_MESSAGE 投票即将结束通知
     * @SCHOOL_VATE_END_MESSAGE 投票结束通知
     * @PUBLISH_RESULT_MESSAGE 公布结果通知
     * @throws JsonException
     */
    private static $messageTypeArray = [
        'NEW_CONTEST_START_MESSAGE' => ['className' => 'NewContestStartMessage', 'queueName' => 'NewContestStartMessageQueue'],
        'SCHOOL_APPLY_SUCCESS_MESSAGE' => ['className' => 'SchoolApplySuccessMessage', 'queueName' => 'SchoolApplySuccessMessageQueue'],
        'SCHOOL_SUBMIT_WORK_END_MESSAGE' => ['className' => 'SchoolSubmitWorkEndMessage', 'queueName' => 'SchoolSubmitWorkEndMessageQueue'],
        'SCHOOL_VATE_START_MESSAGE' => ['className' => 'SchoolVateStartMessage', 'queueName' => 'SchoolVateStartMessageQueue'],
        'SCHOOL_VATE_END_BEFORE_MESSAGE' => ['className' => 'SchoolVateEndBeforeMessage', 'queueName' => 'SchoolVateEndBeforeMessageQueue'],
        'SCHOOL_VATE_END_MESSAGE' => ['className' => 'SchoolVateEndMessage', 'queueName' => 'SchoolVateEndMessageQueue'],
        'PUBLISH_RESULT_MESSAGE' => ['className' => 'PublishResultMessage', 'queueName' => 'PublishResultMessageQueue']
    ];

    /**
     * @param $data
     * @param $type
     * @throws JsonException
     */
    public static function addToQueue($data, $type): void
    {
        self::addToJobQueue($data, $type);
    }

    /**
     * @param $jobData
     * @param $type
     * @throws JsonException
     */
    private static function addToJobQueue($jobData, $type): void
    {
        $jobHandlerClassName = self::$messageTypeArray[$type]['className']::class;
        $jobQueueName = self::$messageTypeArray[$type]['queueName'] . config('queue.server_flag');
        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName); //成功则返回该队列任务的id

        aliCloudLog([
            'topic' => 'template_message_addToJobQueue',
            'params' => \GuzzleHttp\json_encode([
                'jobData' => $jobData,
                'jobHandlerClassName' => $jobHandlerClassName,
                'jobQueueName' => $jobQueueName,
                'isPushed' => $isPushed,
            ], JSON_UNESCAPED_UNICODE),
        ]);
    }

    /**
     * 发送模板消息（消费模板消息队列）
     * @param $userData
     * @param $templateName
     * @param $templateData
     */
    public static function sendMessage($userData, $templateName, $templateData): void
    {
        $sendData = self::createMessageData($userData, $templateName, $templateData);
        self::doSend($userData, $sendData);
    }

    private static function createMessageData($userData, $templateName, $templateData): array
    {
        $template = (new TemplateFactory($templateName, $templateData))->getTemplate();
        return $template->getSendData($userData);
    }

    private static function doSend($userData, $sendData): bool
    {
        $wxoa = Facade::officialAccount();
        $sendData['touser'] = $userData['openid'];
        try {
            $wxoa->template_message->send($sendData);
        } catch (InvalidArgumentException $e) {
        } catch (InvalidConfigException $e) {
        }

        // {"errcode":0,"errmsg":"ok","msgid":1652660129193852928}
        // {"errcode":40165,"errmsg":"invalid weapp pagepath rid: 5fd9a2cd-7fa4ad15-52dec11d"}

        return true;
    }
}
